package service

import (
	"dks-goweb/model"
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strings"
)

func QueryCardZdPool(cardNUM string) (model.TransformedResponse, error) {
	// 定义请求的URL和表单数据
	urlStr := "https://cmp.zdm2m.com/tWxCardInfoController.do?queryWxCardRechargeRecord"
	formData := url.Values{}

	formData.Set("cardNo", cardNUM)
	// 创建HTTP POST请求
	req, err := http.NewRequest("POST", urlStr, strings.NewReader(formData.Encode()))
	if err != nil {
		log.Fatalf("创建请求失败: %v", err)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	// 发送请求并获取响应
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Print("发送请求失败: %v", err)
		return model.TransformedResponse{CardDealer: "未知", Msg: "发送请求失败"}, err
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Print("读取响应失败: %v", err)
		return model.TransformedResponse{CardDealer: "未知", Msg: "读取响应失败"}, err
	}

	// 解析响应的JSON数据到结构体
	var originalResponse model.OriginalResponse
	err = json.Unmarshal(body, &originalResponse)
	if err != nil {
		log.Print("解析JSON失败: %v", err)
		return model.TransformedResponse{CardDealer: "未知", Msg: "解析JSON失败"}, err
	}

	// 转换数据到新的结构体
	var transformedObjList []model.TransformedObj
	for _, item := range originalResponse.Obj {
		transformedObj := model.TransformedObj{
			Packagename: item.Packagename,
		}
		transformedObjList = append(transformedObjList, transformedObj)
	}

	transformedResponse := model.TransformedResponse{

		Obj:     transformedObjList,
		Msg:     originalResponse.Msg,
		Success: originalResponse.Success,
	}

	if strings.Contains(transformedResponse.Msg, "找不到卡信息") {
		transformedResponse.CardDealer = "未知"
	} else if strings.Contains(transformedResponse.Msg, "操作成功") {
		transformedResponse.CardDealer = "中点物联"
	}
	return transformedResponse, nil
}
